package util;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class BlockingThreadPool1 {

	public int capacity, count = 0;

	public ReentrantLock lock = new ReentrantLock(true);

	public Condition notFull = lock.newCondition();

	public BlockingThreadPool1(int capacity) {
		this.capacity = capacity;
	}

	public void add(final Runnable runbl) {
		lock.lock();
		try {
			while (count == capacity)
				notFull.await();
			new Thread(new Runnable() {
				@Override
				public void run() {
					runbl.run();
					signal();
				}
			}).start();
			count++;
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public void signal() {
		lock.lock();
		try {
			count--;
			notFull.signal();
		} finally {
			lock.unlock();
		}
	}

	public int remainingCapacity() {
		return capacity - count;
	}

}